<?php 
    require_once '../../common/DBHelper.php';
    // 1. 先获取从前端传递回来的参数
    // a.分页需要的数据
    $currentPage = $_POST['currentPage'];
    $pageSize = $_POST['pageSize'];
    // b.条件筛选需要的数据
    $category_id = $_POST['category_id'];
    $status = $_POST['status'];

    // 连接数据库，拼接sql语句
    $conn = conn();
    $sql = "SELECT p.id,title,nickname,created,p.`status`,c.`name` FROM posts p 
    LEFT JOIN users ON p.user_id=users.id
    LEFT JOIN categories c ON p.category_id = c.id ";
    // 准备将降序排序放在判断条件下
    $order = " ORDER BY created DESC";
    // 判断条件，拼接sql语句
    $temp = "";
    // 判断category_id和status 如果不是all，就要把条件加上
    if($category_id != 'all' || $status != 'all'){
        $temp .= " where ";
    }
    // 判断分类id
    if($category_id != "all"){
        $temp .= " p.category_id = '{$category_id}' ";
    }
    // 判断状态
    if($status != "all"){
        // 判断是否为两个条件
        if($category_id !="all"){
            // 如果是两个条件，需要加上一个and两个条件隔开
            $temp .= " and ";
        }
        $temp .= " p.`status` = '{$status}'";
    }
    $sql .= $temp;
    $sql .= $order;
    // 把分页的sql语句补全
    $offset = ($currentPage -1 ) * $pageSize;
    $sql .= " limit {$offset},{$pageSize}";

    // 继续完成获取总条数的代码
    $sqlCt = "SELECT count(*) as total FROM posts p ";
    // 还要根据条件拼接sql语句
    $sqlCt .= $temp;

    $countRes = query($conn,$sqlCt);
    $total = $countRes[0]['total'];
    // 执行sql语句
    $result = query($conn,$sql);
    $response = ['code' => 0,'msg' => '操作失败'];
        if($result){
        $response['code'] = 1;
        $response['msg'] = '操作成功';
        $response['data'] = $result;
        $response['dataCount'] = $total;
        }
    echo json_encode($response,JSON_UNESCAPED_UNICODE);
?>